from flask import Blueprint, request
from models import *
from json import dumps
from mail import sendMail

borrow = Blueprint('borrow', __name__)


@borrow.route('/api/borrowReasonType', methods=['GET'])
def getBorrowReasonType():
    return {i.reasonType: i.level for i in BorrowReasonType.query.filter(BorrowReasonType.available == 1).all()}


@borrow.route('/api/reserve', methods=['POST'])
def reserve():
    """
    {
        "name": "王新昀",
        "identity": "10194500047",
        "phone_number": "19121711569",
        "reason_type": "教信系学生个人自立项目",
        "reason_name": "借用测试",
        "device": {
            "松下4K 180": [1, 2]
        },
        "receive_time": "2022-02-24T13:42:05",
        "return_time": "2022-02-24T13:42:05",
        "note": "测试专用"
    }
    :return:
    """
    jsonData = request.json

    record = DeviceBorrow()
    record.name = jsonData['name']
    record.identity = jsonData['identity']
    record.phone_number = jsonData['phone_number']
    record.reason_type = jsonData['reason_type']
    record.reason_name = jsonData['reason_name']
    record.state = '未处理'
    record.receive_time = jsonData['receive_time']
    record.return_time = jsonData['return_time']
    record.note = jsonData['note']

    device_category = jsonData['device']

    sqlStrHead = "update DeviceStatus set state='预定' where state='在库' AND (FALSE "
    sqlStrCandition = "OR (name='%s' and ID in %s)"
    sqlStrTail = ")"
    sql = sqlStrHead

    device_category_copy = device_category.copy()

    for category in device_category:
        for name in device_category[category]:
            this_device = device_category[category][name]
            if len(this_device) == 0:
                device_category_copy[category].pop(name)
                continue
            for i in this_device:
                if type(i) is not int:
                    print(type(i))
                    db.session.rollback()
                    return "Forbidden", 400
            range_str = str(tuple(this_device)) if len(this_device) != 1 else "(%d)" % this_device[0]
            if ')' not in name:
                sql += sqlStrCandition % (name, range_str)
            else:
                db.session.rollback()
                return "Forbidden", 400
        if len(device_category[category]) == 0:
            device_category_copy.pop(category)

    device_category = device_category_copy
    sql += sqlStrTail
    db.session.execute(sql)
    record.device = dumps(device_category, ensure_ascii=False)
    db.session.add(record)

    sql_result = db.session.execute("""
        select Email from Member WHERE `Name` = (
	        select * from (
		select ThisWeek from HandOver ORDER BY Time DESC LIMIT 1
	        ) temp_tab
        );
    """)
    result = [row[0] for row in sql_result][0]
    print(result)
    sendMail("新设备借用申请", """
    借用人：%s\r\n
    项目类型：%s\r\n
    项目名称：%s\r\n
    请及时处理哦~\r\n
    此邮件为壹幕工作室程序自动发送，请勿回复
    """ % (jsonData['name'], jsonData['reason_type'], jsonData['reason_name']), result)
    return '提交成功'






